package com.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    public static DataSource ds = null;
    static {
        try {
            // 1. 加载druid.properties配置文件
            InputStream resourceAsStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            // 2. 创建Druid连接池对象。
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 3. 返回连接池对象
    public static DataSource getDataSource(){
        return ds;
    }

    // 4. 从连接池中 获取连接对象Connection的方法
    public static Connection getConnection() throws SQLException {
        Connection connection = ds.getConnection();
        return connection;
    }
}
